package com.du.cloud.security.service;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import com.du.cloud.common.base.constant.CommonConstants;
import com.du.cloud.common.base.constant.RedisKeyConstants;
import com.du.cloud.common.base.constant.SecurityConstants;
import com.du.cloud.common.base.utils.Result;
import com.du.cloud.service.admin.api.feign.RemoteUserService;
import com.du.cloud.service.admin.api.model.dto.SysUserDTO;
import com.du.cloud.service.admin.api.model.dto.UserInfo;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;

/**
 * Desc:
 * Author: dushuang
 * Date: 2020/5/25
 **/
@Slf4j
@Service
@RequiredArgsConstructor
public class CustomUserDetailsServiceImpl implements UserDetailsService {

    private final RemoteUserService remoteUserService;
    private final CacheManager cacheManager;

    @Override
    public TokenUser loadUserByUsername(String username) throws UsernameNotFoundException {
        Result<UserInfo> result = remoteUserService.info(username, SecurityConstants.FROM_IN);
        TokenUser userDetails = getUserDetails(result);

        return userDetails;
    }

    private TokenUser getUserDetails(Result<UserInfo> result) {
        if (result == null || result.getData() == null) {
            throw new UsernameNotFoundException("用户不存在");
        }

        UserInfo info = result.getData();
        Set<String> dbAuthsSet = new HashSet<>();
        if (CollectionUtil.isNotEmpty(info.getRoles())) {
            // 获取角色
            info.getRoles().forEach(role -> dbAuthsSet.add(SecurityConstants.ROLE_PREFIX + role));
            // 获取资源权限
            dbAuthsSet.addAll(info.getPermissions());

        }
        Collection<? extends GrantedAuthority> authorities
                = AuthorityUtils.createAuthorityList(dbAuthsSet.toArray(new String[0]));
        SysUserDTO user = info.getUser();

        // 构造security用户
        return new TokenUser(
                user.getId(),
                user.getPhone(),
                user.getLoginName(),
                SecurityConstants.BCRYPT + user.getPassword(),
                user.getLoginFlag() == CommonConstants.STATUS_NORMAL,
                authorities);
    }
}
